package com.diorsunion.hedge.bo.db;

import com.diorsunion.hedge.common.BOResult;
import com.diorsunion.hedge.constant.Constants;
import com.diorsunion.hedge.dal.entity.account.Account;
import com.diorsunion.hedge.dal.entity.account.AccountAssets;
import com.diorsunion.hedge.dal.entity.account.User;
import com.diorsunion.hedge.dal.repository.account.AccountAssetsRepository;
import com.diorsunion.hedge.dal.repository.account.AccountRepository;
import com.diorsunion.hedge.dto.BorkerAccount;
import com.diorsunion.hedge.enums.AccountType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * //TODO 待测试
 * 账户管理业务类
 * Created by custe on 2016/8/9.
 */
@Component
public class AccountBO {
    @Resource
    AccountRepository accountRepository;
    @Resource
    AccountAssetsRepository accountAssetsRepository;

    /**
     * 登录,如帐号不存在则往数据库插入一个新的account信息，如存在，则更改lastLoginTime
     */
    public BOResult addNewAccount(BorkerAccount borkerAccount){
        Account account = new Account();
        account.code = borkerAccount.code;
        account.borkerType = borkerAccount.borkerType;
        List<Account> existList = accountRepository.find(account);
        if(!CollectionUtils.isEmpty(existList)){
            return BOResult.successResult();
        }
        if(account.accountType==null){
            account.accountType = AccountType.S;
        }
        if(account.currency==null){
            account.currency = Currency.getInstance(Locale.US);
        }
        accountRepository.insert(account);
        return  BOResult.successResult();
    }

    public List<Account> findAccountByUser(User user, Date begin, Date end){
        if(user==null){
            return Constants.emptyList;
        }
        List<Account> accountList = accountRepository.findByUser(user);
        if(begin!=null && end!=null){
            accountList.parallelStream().forEach(account -> setAccountAssets(account,begin,end));
        }
        return accountList;
    }

    public void setAccountAssets(Account account, Date begin, Date end){
        if(account==null || begin ==null || end==null){
            return;
        }
        List<AccountAssets> accountAssetsList = accountAssetsRepository.findByDate(account,begin,end);
        account.accountAssetsList = accountAssetsList;
    }

    public void insertAccountAssets(Account account, AccountAssets accountAssets) {
        List<Account> accountList = accountRepository.find(account);
        accountList.forEach(x -> {
            accountAssets.account = x;
            accountAssetsRepository.insert(accountAssets);
        });
    }
}
